package com.sdkx.wear_os.utils

import android.content.Context
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.net.Uri
import android.widget.ImageView
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.luck.picture.lib.engine.CompressFileEngine
import com.luck.picture.lib.engine.CropFileEngine
import com.luck.picture.lib.interfaces.OnKeyValueResultCallbackListener
import com.luck.picture.lib.style.PictureSelectorStyle
import com.luck.picture.lib.style.SelectMainStyle
import com.luck.picture.lib.style.TitleBarStyle
import com.luck.picture.lib.utils.DateUtils
import com.luck.picture.lib.utils.StyleUtils
import com.sdkx.wear_os.R
import com.yalantis.ucrop.UCrop
import com.yalantis.ucrop.UCropImageEngine
import top.zibin.luban.Luban
import top.zibin.luban.OnNewCompressListener
import java.io.File

/**
 * 配制UCrop，可根据需求自我扩展
 *@param isCircle 是否是圆形裁剪
 * @return
 */
fun buildOptions(context: Context, isCircle: Boolean): UCrop.Options {
    val options = UCrop.Options()
    options.setHideBottomControls(true)
    options.setFreeStyleCropEnabled(false)
    options.setShowCropFrame(false)
    options.setShowCropGrid(false)
    //true 圆形裁剪
    options.setCircleDimmedLayer(isCircle)
    options.withAspectRatio(1f, 1f)
    options.setCropOutputPathDir(getSandboxPath(context))
    options.isCropDragSmoothToCenter(false)
//        options.setSkipCropMimeType(*getNotSupportCrop())
    options.isForbidCropGifWebp(false)
    options.isForbidSkipMultipleCrop(false)
    options.setMaxScaleMultiplier(100f)
    options.setStatusBarColor(ContextCompat.getColor(context, R.color.gray_393A3E))
    options.setToolbarColor(ContextCompat.getColor(context, R.color.gray_393A3E))
    options.setToolbarWidgetColor(
        ContextCompat.getColor(
            context,
            R.color.white
        )
    )
    val selectorStyle = PictureSelectorStyle()
    val mainStyle: SelectMainStyle = selectorStyle.selectMainStyle
    val isDarkStatusBarBlack = mainStyle.isDarkStatusBarBlack
    val statusBarColor = mainStyle.statusBarColor
    options.isDarkStatusBarBlack(isDarkStatusBarBlack)
    if (StyleUtils.checkStyleValidity(statusBarColor)) {
        options.setStatusBarColor(statusBarColor)
        options.setToolbarColor(statusBarColor)
    } else {
        options.setStatusBarColor(ContextCompat.getColor(context, R.color.gray_393A3E))
        options.setToolbarColor(ContextCompat.getColor(context, R.color.gray_393A3E))
    }
    val titleBarStyle: TitleBarStyle = selectorStyle.titleBarStyle
    if (StyleUtils.checkStyleValidity(titleBarStyle.titleTextColor)) {
        options.setToolbarWidgetColor(titleBarStyle.titleTextColor)
    } else {
        options.setToolbarWidgetColor(
            ContextCompat.getColor(
                context,
                R.color.white
            )
        )
    }
    return options
}

/**
 * 创建自定义输出目录
 *
 * @return
 */
fun getSandboxPath(context: Context): String {
    val externalFilesDir: File = context.getExternalFilesDir("")!!
    val customFile = File(externalFilesDir.absolutePath, "Sandbox")
    if (!customFile.exists()) {
        customFile.mkdirs()
    }
    return customFile.absolutePath + File.separator
}

/**
 * 自定义裁剪
 */
class ImageFileCropEngine(context: Context, isCircle: Boolean) : CropFileEngine {
    var context: Context
    //是否圆形裁剪
    var isCircle: Boolean = false

    init {
        this.context = context
        this.isCircle = isCircle
    }

    override fun onStartCrop(
        fragment: Fragment,
        srcUri: Uri,
        destinationUri: Uri,
        dataSource: java.util.ArrayList<String>,
        requestCode: Int
    ) {
        val options: UCrop.Options = buildOptions(context, isCircle)
        val uCrop = UCrop.of(srcUri, destinationUri, dataSource)
        uCrop.withOptions(options)
        uCrop.setImageEngine(object : UCropImageEngine {
            override fun loadImage(context: Context, url: String, imageView: ImageView) {
                Glide.with(context).load(url).override(180, 180).into(imageView)
            }

            override fun loadImage(
                context: Context,
                url: Uri,
                maxWidth: Int,
                maxHeight: Int,
                call: UCropImageEngine.OnCallbackListener<Bitmap>
            ) {
                Glide.with(context).asBitmap().load(url).override(maxWidth, maxHeight)
                    .into(object : CustomTarget<Bitmap>() {
                        override fun onResourceReady(
                            resource: Bitmap,
                            transition: Transition<in Bitmap>?
                        ) {
                            call.onCall(resource)
                        }

                        override fun onLoadCleared(placeholder: Drawable?) {
                            call.onCall(null)
                        }

                    })
            }
        })
        uCrop.start(fragment.requireActivity(), fragment, requestCode)
    }
}

/**
 * 自定义压缩
 */
class ImageFileCompressEngine : CompressFileEngine {
    override fun onStartCompress(
        context: Context,
        source: java.util.ArrayList<Uri>,
        call: OnKeyValueResultCallbackListener
    ) {
        Luban.with(context).load(source).ignoreBy(100).setRenameListener { filePath ->
            val indexOf = filePath.lastIndexOf(".")
            val postfix = if (indexOf != -1) filePath.substring(indexOf) else ".jpg"
            DateUtils.getCreateFileName("CMP_") + postfix
        }.setCompressListener(object : OnNewCompressListener {
            override fun onStart() {}
            override fun onSuccess(source: String, compressFile: File) {
                call.onCallback(source, compressFile.absolutePath)
            }

            override fun onError(source: String, e: Throwable) {
                call.onCallback(source, null)
            }
        }).launch()
    }
}